package org.hairball;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public class ClassJarReader {
    public byte[] nextClass() {
        return null;
    }

    public List<byte[]> read(String jarFileToLoad) throws IOException {
        List<byte[]> listOfClasses = new ArrayList<byte[]>();

        JarFile jarFile = new JarFile(new File(jarFileToLoad));
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;

        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            try {
                JarEntry entry = entries.nextElement();

                if (!entry.isDirectory() && isClassFile(entry)) {
                    inputStream = jarFile.getInputStream(entry);
                    baos = new ByteArrayOutputStream();
                    int c;
                    while ((c = inputStream.read()) != -1) {
                        baos.write(c);
                    }
                    listOfClasses.add(baos.toByteArray());
                }
            } finally {
                closeSafely(inputStream);
                closeSafely(baos);
            }
        }
        return listOfClasses;
    }

    private boolean isClassFile(JarEntry entry) {
        return (entry.getName().endsWith("class"));
    }

    private void closeSafely(ByteArrayOutputStream baos) {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ignored) {

            }
        }
    }

    private void closeSafely(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ignored) {

            }
        }
    }
}
